package org.dpms.controller.common;

import java.util.Calendar;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.dpms.entity.User;
import org.dpms.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.dubbo.config.annotation.Reference;

@Controller
public class LoginContorller {
	
	@Reference(version = "1.0.0")
	IUserService userService;

	 /** 
     *登录 
     * @param model 
     * @return 
//     */  
//    @RequestMapping(value="login")  
//    public ModelAndView  login(){  
//        return new ModelAndView("login");  
//    } 
    
    /** 
     *登录 
     * @param model 
     * @return 
     */  
    @RequestMapping(value="register")  
    public ModelAndView register(){  
        return new ModelAndView("register");  
    } 
    
    /** 
     *登录 
     * @param model 
     * @return 
     */  
    @RequestMapping(value="login")  
    @ResponseBody
    public String doLogin(String username,String password){  
    	 // 创建Subject实例
        Subject currentUser = SecurityUtils.getSubject();
        // 将用户名及密码封装到UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken("guoq", "admin123");
        try {
            currentUser.login(token);
            // 判断当前用户是否登录
            if (currentUser.isAuthenticated() == true) {
                return "登录成功";
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("登录失败");
        }
        return "登录失败";
    	
    	
    } 
    
    @RequestMapping(value="doRegister")  
		public ModelAndView doRegister(String username,String password,String email) {
    		User user = new User();
    		user.setNickname(username);
    		user.setPswd(password);
    		user.setEmail(email);
    		user.setCreateTime(Calendar.getInstance().getTime());
			boolean result = userService.register(user);
			if(result){
				return new ModelAndView("login");
			}
			return new ModelAndView("register");
		}
}
